#include "fbpool.h"


#define FBPOOL_MAGIC "FBPL"

#define FPS_UPDATE_INTERVAL 60
#define ERR(...) do { fprintf(stderr, __VA_ARGS__); } while (0)
#define FMT_NUM_PLANES 1
#define BUFFER_COUNT 3
int first = 0;
int fd = -1;
RockchipRga *rga;
bo_t bo_dst;
bo_t bo_src;
rga_info_t rga_info_src;
rga_info_t rga_info_dst;
char *cap_buf[BUFFER_COUNT];
char *video_buf;
char *resize_buf;
int cap_dma_fd[BUFFER_COUNT], video_dma_fd, resize_dma_fd;
rga_buffer_t src[BUFFER_COUNT] = {};
rga_buffer_t video = {};
rga_buffer_t resize_t = {};
rga_buffer_handle_t cap_handle[BUFFER_COUNT], video_handle,resize_handle;
int cap_width, cap_height, cap_format;
int resize_width, resize_height, resize_format;
int video_width, video_height, video_format;
int cap_buf_size, video_buf_size,resize_buf_size;
cv::Mat* rgbamat = NULL;
#define CLEAR(x) memset(&(x), 0, sizeof(x))

static int xioctl(int fh, int request, void *arg)
{
        int r;
        do {
                r = ioctl(fh, request, arg);
        } while (-1 == r && EINTR == errno);
        return r;
}

static void log_fps(void) {
    struct timeval tv;
    uint64_t curr_time;
    float fps;

    static uint64_t last_fps_time = 0;
    static unsigned frames = 0;

    if (!last_fps_time) {
        gettimeofday(&tv, NULL);
        last_fps_time = tv.tv_sec * 1000 + tv.tv_usec / 1000;
    }

    if (++frames % FPS_UPDATE_INTERVAL)
        return;

    gettimeofday(&tv, NULL);
    curr_time = tv.tv_sec * 1000 + tv.tv_usec / 1000;

    fps = 1000.0f * FPS_UPDATE_INTERVAL / (curr_time - last_fps_time);
    last_fps_time = curr_time;

    printf("[FBPOOL] FPS: %6.1f || Frames: %u\n", fps, frames);
}
int open_video(void)
{
     fd = open("/dev/video0", O_RDWR /* required */ /*| O_NONBLOCK*/, 0);

    if (-1 == fd) {
		printf("open video err\n");
    	return -1;
    }

    return 0;

}
static void init_rga()
{
    printf("init rga\n");
    cap_width = 1920;
    cap_height = 1080;
    cap_format = RK_FORMAT_BGR_888;

    resize_width = 1920;
    resize_height = 1080;
    resize_format = RK_FORMAT_BGR_888;

    video_width = 1920;
    video_height = 1080;
    video_format = RK_FORMAT_RGBA_8888;
    cap_buf_size = cap_width * cap_height * get_bpp_from_format(cap_format);
    video_buf_size = video_width * video_height * get_bpp_from_format(video_format);
    resize_buf_size = resize_width * resize_height * get_bpp_from_format(resize_format);
    printf("%d %d \n",cap_buf_size,video_buf_size);
}

static void init_display_buf()
{
    int ret = 0;
    int i;
    for(i = 0; i < BUFFER_COUNT; i++) {
        ret = dma_buf_alloc(DMA_HEAP_UNCACHE_PATH, cap_buf_size, &cap_dma_fd[i], (void **)&cap_buf[i]);
        if (ret < 0) {
            printf("alloc cap_buf dma_heap buffer failed!\n");
	    return;
        }
        cap_handle[i] = importbuffer_fd(cap_dma_fd[i], cap_buf_size);
	if(cap_handle[i] == 0) {
	    printf("import cap_handle error!\r");
	    goto free_buf;
	}
        printf("cam_dma_fd[%d] = %d\n",i,cap_dma_fd[i]);
    	src[i] = wrapbuffer_handle(cap_handle[i], cap_width, cap_height, cap_format);
    }

    ret = dma_buf_alloc(DMA_HEAP_UNCACHE_PATH, video_buf_size, &video_dma_fd, (void **)&video_buf);
    if (ret < 0) {
        printf("alloc video dma_heap buffer failed!\n");
	goto free_buf;
    }

    video_handle = importbuffer_fd(video_dma_fd, video_buf_size);
    if (video_handle == 0) {
        printf("import video_handle error!\n");
        goto free_buf;
    }
    video = wrapbuffer_handle(video_handle, video_width, video_height, video_format);

    ret = dma_buf_alloc(DMA_HEAP_UNCACHE_PATH, resize_buf_size, &resize_dma_fd, (void **)&resize_buf);
    if (ret < 0) {
        printf("alloc video dma_heap buffer failed!\n");
        return; 
    }

    resize_handle = importbuffer_fd(resize_dma_fd, resize_buf_size);
    if (resize_handle == 0) {
        printf("import video_handle error!\n");
        goto free_buf;
    }
    resize_t = wrapbuffer_handle(resize_handle, resize_width, resize_height, resize_format);
    return;
		
free_buf:
    for(i = 0; i < BUFFER_COUNT; i++)
        dma_buf_free(cap_buf_size, &cap_dma_fd[i], cap_buf);

    dma_buf_free(video_buf_size, &video_dma_fd, video_buf);
    dma_buf_free(resize_buf_size, &resize_dma_fd, resize_buf);
}
static void init_mmap(void)
{
    struct v4l2_requestbuffers req;

    CLEAR(req);

    req.count = BUFFER_COUNT;
    req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
    req.memory = V4L2_MEMORY_DMABUF;

    if (-1 == xioctl(fd, VIDIOC_REQBUFS, &req)) {
		printf("reqbuf err\n");
		return;
    }

    if (req.count !=  BUFFER_COUNT) {
		printf("buf not exp\n");
		return;
    }
    for (n_buffers = 0; n_buffers < req.count; ++n_buffers) {
        struct v4l2_buffer buf;
        struct v4l2_plane planes[FMT_NUM_PLANES];
        CLEAR(buf);
	CLEAR(planes);

        buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
        buf.memory = V4L2_MEMORY_DMABUF;
        buf.index = n_buffers;
		
        buf.m.planes = planes;
	buf.length = FMT_NUM_PLANES;

        if (-1 == xioctl(fd, VIDIOC_QUERYBUF, &buf))
                printf("VIDIOC_QUERYBUF err\n");

	buf.m.planes[0].m.fd = cap_dma_fd[n_buffers];
	buf.m.planes[0].length = cap_width * cap_height * 3;
	//buf.m.fd = cap_dma_fd[n_buffers];
        if (-1 == xioctl(fd, VIDIOC_QBUF, &buf))
			printf("qbuf err\n");

    }
}

 void init_device(void)
{
    struct v4l2_capability cap;
    struct v4l2_format fmt;

    init_rga();

    if (-1 == xioctl(fd, VIDIOC_QUERYCAP, &cap)) {
    	printf("is no V4L2 devicen\n");
		return;
    }

    if (!(cap.capabilities & V4L2_CAP_VIDEO_CAPTURE) &&
            !(cap.capabilities & V4L2_CAP_VIDEO_CAPTURE_MPLANE)) {
			printf("no support cap\n");
			return;
    }

    if (!(cap.capabilities & V4L2_CAP_STREAMING)) {
			printf("no support stream\n");
			return;
    }
    
    CLEAR(fmt);
    fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
    fmt.fmt.pix.width = cap_width;
    fmt.fmt.pix.height = cap_height;
    fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_RGB24;
    fmt.fmt.pix.field = V4L2_FIELD_NONE;

    if (-1 == xioctl(fd, VIDIOC_S_FMT, &fmt)) {
			printf("no support fmt\n");
			return;
    }



    init_display_buf();

    init_mmap();
}

void start_capturing(void)
{
    enum v4l2_buf_type type;

    type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
    if (-1 == xioctl(fd, VIDIOC_STREAMON, &type))
	    printf("stream on err\n");
	printf("start succ\n");
}

static void process_buffer(int i)
{
#if 1
    int ret, col;
    //ret = imresize(src[i], resize_t);
    //if (ret == IM_STATUS_SUCCESS) {
        //printf("running success!\n");
    //} else {
        //printf("running failed \n");
    //}
    ret = imcvtcolor(src[i], video, resize_format, video_format);
    if (ret == IM_STATUS_SUCCESS) {
        //printf("running success!\n");
    } else {
        //printf("running failed\n"); 
    }
    drm_render(video_buf, 32,
                  1920, 1080, 1920*4);
        //log_fps();
#endif
#if 0
   
    cv::Mat yuvmat(cv::Size(640,480 ), CV_8UC2, cap_buf[i]);
    cv::Mat rgbmat(cv::Size(640, 480), CV_8UC3);
    cv::cvtColor(yuvmat, rgbmat, CV_YUV2RGB_YVYU);
    cv::imshow("video", rgbmat);
    cv::waitKey(1);
#endif
}

int read_frame()
{
    static int nCnt = 0;
    struct v4l2_buffer buf;
    struct v4l2_plane planes[FMT_NUM_PLANES];
    int i, bytesused;

    CLEAR(buf);
    CLEAR(planes);

    buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
    buf.memory = V4L2_MEMORY_DMABUF;
    buf.m.planes = planes;
    buf.length = FMT_NUM_PLANES;

    if (-1 == xioctl(fd, VIDIOC_DQBUF, &buf))
	    printf("err dqbuf\n");


    i = buf.index;

    bytesused = buf.bytesused;
    process_buffer(i);

    printf("read_frame %d \r\n",nCnt);
    nCnt++;
    //buf.m.planes[0].m.fd = cap_dma_fd[n_buffers];
    //buf.m.planes[0].length = cap_width * cap_height * 3;
    if (-1 == xioctl(fd, VIDIOC_QBUF, &buf))
	    printf("err qbuf\n");

    return 1;
}



